import express from 'express'
import { verifyTokenMiddleware, createAccessToken, createRefreshToken, verifyRefreshToken } from './utils/token.js'

const app = express()
const port = 3000
app.use(express.json())
app.use('*', (req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173')
  res.setHeader('Access-Control-Allow-Credentials', true)
  res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type')
  //   console.log('===req', req.headers['Authorization'])
  next()
})
// token错误处理中间件
// app.use(tokenErrorMiddle)
// token校验中间件
app.use(verifyTokenMiddleware)

// app.get('/', (req, res) => {
//   res.send('hello server 3000')
// })
let userInfo = {}
app.post('/v1/login', (req, res) => {
  const { username, password } = req.body
  console.log('username=' + username, 'password=' + password)
  const userId = 1
  setTimeout(() => {
    userInfo = {
      username,
      userId,
    }
    res.json({
      code: 200,
      msg: 'success',
      data: {
        username,
        userId,
        accessToken: createAccessToken({ userId, username }),
        refreshToken: createRefreshToken({ userId, username }),
      },
    })
  }, 500)
})
app.post('/v1/refresh', (req, res) => {
  const { refreshToken } = req.body
  verifyRefreshToken(refreshToken)
    .then((result) => {
      const newToken = createAccessToken({ userId: userInfo.userId, username: userInfo.username })
      console.log('refresh newToken', result, newToken)
      userInfo = { ...result }
      res.status(200).send({
        code: 200,
        message: 'token已刷新，长token有效',
        data: newToken,
      })
    })
    .catch((error) => {
      console.log('error catch', JSON.stringify(error))
      // 长token也过期了
      res.status(403).send({
        code: 403,
        message: '长token已过期',
      })
    })
})
app.get('/v1/getUser', (req, res) => {
  const token = req.headers['authorization']
  console.log('getUser中的', token)
  setTimeout(() => {
    console.log('userInfo', userInfo)
    res.send({
      ...userInfo,
    })
  }, 500)
})
// jsonp支持
app.get('/v1/jsonp', (req, res) => {
  const callback = req.query.cb || req.query.callback
  setTimeout(() => {
    res.send(`${callback}(${JSON.stringify(req.query)})`)
  }, 500)
})
// 测试接口唯一
app.post('/v1/testUnique', (req, res) => {
  setTimeout(() => {
    res.json({
      code: 200,
      msg: 'success',
      data: {
        message: '测试接口唯一',
      },
    })
  }, 500)
})
app.listen(port, () => {
  console.log('server is runing at http://localhost:' + port)
})
